//app.js
import Count from './utils/realtimeCount.js'
var count = new Count();
App({
  data: {
    commonUrl: 'https://xiaoyouxi.coco.cn/',
    // commonUrl:'http://dev.coco.cn/',
    dir:'Server/GameCenter',
    judgeCode: 'Server/Wechat/judgeCode',
    pushNotification:'Server/gameCenter/pushNotification',
    gift:'Server/GameCenter/gift',
    homepage:'Server/GameCenter/homepage',
    taskUrl:'Server/GameCenter/task',
    appflag:'xcx06',
    isIPhoneX: false,
    optGlobal: {},
    openIdGlobal: '',
    appAlreadyTips: false,
    location_wxid:'',
    isIOS:false,
    isIOSVerHigh:false,
    shareTpl: [
      `高能预警，没想到你是这样的小游戏`,
      `高能游戏，释放你的神奇力量`,
      `前方高能预警，复仇者正在集结！`,
      `高能预警！游戏有毒！请慎入！`,
      `高能游戏大爆发，这可能是前所未有的体验`
    ],
    showResiveFlag:false,
    showResiveTip:'',
    showResiveIcon:0,
    countGlobal: count,
    current_num:0,
    game_current_num:0,
    share_current_num:0,
    levels: null,
    coins: [
      { level: 1, name: '平民', min: 0, max: 300 },
      { level: 2, name: '青铜', min: 300, max: 1000 },
      { level: 3, name: '白银', min: 1000, max: 2000 },
      { level: 4, name: '黄金', min: 2000, max: 5000 },
      { level: 5, name: '铂金', min: 5000, max: 20000 },
      { level: 6, name: '钻石', min: 20000, max: 50000 },
      { level: 7, name: '星耀', min: 50000, max: 100000 },
      { level: 8, name: '荣耀王者', min: 100000, max: 90000000 },
    ]
  },
  //判断等级
  judgeGrade(coin) {
    let _this = this;
    this.data.coins.forEach(function (v, k) {
      //等级为0
      if (coin == 0) {
        _this.data.levels= v.name ;
        return false;
      };

      if (coin > v.min && coin <= v.max) {
        _this.data.levels = v.name;
        return false;
      };
      //等级最高判断条件为min
      if (v.level == 8 && coin > v.min) {
        _this.data.levels = v.name;
        return false;
      };
    })
  },
  globalData: {
    userInfo: null
  },

  onLaunch: function(opt) {
    this.log({
      "onLaunch": this.data
    });

    count.setEnv(opt);
    this.data.optGlobal = opt;
    // 展示本地存储能力
    var logs = wx.getStorageSync('logs') || []

    logs.unshift(Date.now())
    wx.setStorageSync('logs', logs)
    wx.getSystemInfo({
      success: res => {
        const isIpx = res.model.toString().includes('iPhone X');
        this.data.isIPhoneX = isIpx;
        //判断是安卓还是iOS
        let system = res.system,
            version = res.version;
        if (system.indexOf("iOS") != -1 ){
          this.data.isIOS=true;
        }else{
          this.data.isIOS = false;
        }
        //判断ios有没有升级
        if (version === '6.7.1') {
          this.data.isIOSVerHigh = true;
        } else {
          this.data.isIOSVerHigh = false;
        }
      }
    })

    // 获取用户信息
    wx.getSetting({
      success: res => {
        if (res.authSetting['scope.userInfo']) {
          // 已经授权，可以直接调用 getUserInfo 获取头像昵称，不会弹框
          wx.getUserInfo({
            success: res => {
              // 可以将 res 发送给后台解码出 unionId
              this.globalData.userInfo = res.userInfo

              // 由于 getUserInfo 是网络请求，可能会在 Page.onLoad 之后才返回
              // 所以此处加入 callback 以防止这种情况
              if (this.userInfoReadyCallback) {
                this.userInfoReadyCallback(res)
              }
            }
          })
        }
      }
    })
  },
  log(res) {
/*
    wx.request({
      url: 'http://dev.coco.cn/Server/GameCenter/log',
      data: res
    })
    */
  },

  locationApp(appid, imp_data) {
    var _this = this;

    if (typeof imp_data == 'object') {
      imp_data.type = 'inbox';
    }

    wx.hideLoading();

    wx.navigateToMiniProgram({
      appId: appid,
      success(e) {
        _this.data.location_wxid = appid;
        wx.request({
          url: 'https://xiaoyouxi.coco.cn/Server/CrossAd/click',
          data: imp_data
        })
      }
    });

    /*
        wx.navigateToMiniProgram({
          appId: 'wx011a82fedef36d59',
          path: '',
          extraData: { location: 'wx4788afbc2b950d42', imp_data: '886886' },
          envVersion:'trial',
          success(e) {
            console.log('navigateToMiniProgram success', e);
          }
        });
        */

  },
  onShow(opt) {
    if (this.data.isIOS && this.data.isIOSVerHigh) {
      if (opt.scene == 1103 || opt.scene == 1104 || opt.scene == 1023) {
          wx.setStorageSync('alreadyTips', true);
          this.appAlreadyTips = true;
        }
    }
    var _this = this;

    try {

      var location = opt.referrerInfo.extraData.location;
      var imp_data = opt.referrerInfo.extraData.imp_data;

      if (location != undefined && imp_data != undefined) {
        if (location != null && imp_data != null) {

          console.log('data.location_wxid', this.data.location_wxid);

          if (this.data.location_wxid == '') {
            wx.showLoading({
              title: '正在打开'
            });
            this.locationApp(location, imp_data);
          } else {
            //这样每次iOS都能点出来
            this.data.location_wxid = "";
          }

        }
      }

    } catch (e) {
      // console.log('location not isset');
    }

    count.eventReady(function() {
      count.beginTime();
    });
  },
  onHide(e) {
    count.eventReady(function() {
      count.stopTime();
    });


    var sys = wx.getSystemInfoSync();
    var is_ios = sys.system.indexOf('iOS') != -1;
    //iOS关闭后所有页面关闭,安卓则是回道页面所以针对安卓不清空标记
    if (is_ios) {
      this.data.location_wxid = "";
    }
    wx.hideLoading();

    this.log({
      "onHide": this.data
    });
    this.log({
      "onHide": e
    });
  },
  onUnload(e) {
    this.log({
      "onUnload": e
    });

  },
  callLogin(params) {
    return new Promise((resolve, rejected) => {
      wx.login({
        success: res => {
          wx.request({
            url: this.data.commonUrl + this.data.judgeCode,
            data: { code: res.code, appflag: this.data.appflag },
            success: response => {
              wx.showLoading({ title: '登录中' });

              const session_key = response.data.result.session_key;
              if (response.data.result.hasOwnProperty('session_key')) {
                wx.request({
                  method: 'POST',
                  url: this.data.commonUrl + 'Server/Wechat/register',
                  header: {
                    "Content-Type": "application/x-www-form-urlencoded",
                  },
                  data: {
                    session_key,
                    encryptedData: params.encryptedData,
                    iv: params.iv,
                    signature: params.signature,
                    appflag: this.data.appflag
                  },
                  success: res => {
                    if (res.data.code == '0') {
                      resolve({ token: res.data.result.session_id, params: params, expired: 0, uid: res.data.result.uid });

                    } else if (res.data.code == '201') {
                      wx.showToast({
                        title: '登录失败,请重试',
                        icon: 'none'
                      })
                    }
                  }
                })
              }else{
                count.setOpenid(response.data.result.uid);
                count.eventReady(function () {
                  count.beginTime();
                  count.newUserCount();
                });
                wx.setStorageSync('expire_at', response.data.result.expire_at);
                wx.setStorageSync('openid', response.data.result.openid);
                wx.setStorageSync('uid', response.data.result.uid);
                resolve({ token: response.data.result.session_id, params: params, expired: 0, uid: response.data.result.uid });

              }
            }
          })
        }
      })
    }).then((data) => {
      return new Promise((resolve, reject) => {
        wx.setStorageSync('sessionid_pro', data.token);
        resolve({ token: data.token, userinfo: data.params.userInfo, expired: data.expired });
      })
    })
  },
  //计算token是否过期
  effectiveToken(){
    const flag = 7,
      now = new Date(),
      nowstamp = Math.round(new Date().getTime() / 1000).toString(),
      time = wx.getStorageSync('expire_at') - nowstamp,
      days = parseInt(time / (60 * 60 * 24));
    //token有效期均为30天,在过期前调用本接口将会返回新的30天有效期的 session_id 及过期时间,一般情况下应提前7天判断
    if (days < flag) {
      wx.removeStorageSync('sessionid_pro')
      wx.removeStorageSync('expire_at')
      wx.removeStorageSync('openid')
      wx.removeStorageSync('uid')
    }
  }

})
